<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert show-icon center title="注意：只允许为第三级分类设置相关参数" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
            <el-cascader v-model="selectedKeys" :options="catelist" :props="propsConfig" @change="cascaderChange" clearable>
            </el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页部分 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="watchBtn" class="btn" @click="addParams">添加参数</el-button>
          <el-table :data="manyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
                <!-- 输入的文本框 -->
                <el-input class="inputSize" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="mini"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else size="mini" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editParams(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParams(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="watchBtn" class="btn" @click="addAttibute">添加属性</el-button>
          <el-table :data="onlyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
                <!-- 输入的文本框 -->
                <el-input class="inputSize" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="mini"
                  @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加按钮 -->
                <el-button v-else size="mini" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editAttribute(scope.row)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteAttribute(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加动态参数对话框 -->
      <AddParams ref="addParams"></AddParams>
      <!-- 添加静态属性对话框 -->
      <AddAttribute ref="addAttribute"></AddAttribute>
      <!-- 修改动态参数对话框 -->
      <EditParams ref="editParams"></EditParams>
      <!-- 修改静态属性对话框 -->
      <EditAttribute ref="editAttribute"></EditAttribute>
    </el-card>
  </div>
</template>
<script>
import AddParams from '../good/dialog/AddParams'
import AddAttribute from '../good/dialog/AddAttribute'
import EditParams from '../good/dialog/EditParams'
import EditAttribute from '../good/dialog/EditAttribute'
export default {
  components: {
    AddParams,
    AddAttribute,
    EditParams,
    EditAttribute
  },
  data: function () {
    return {
      // 商品分类列表
      catelist: [],
      //  级联选择器绑定的数组
      selectedKeys: [],
      // 级联选择器属性配置
      propsConfig: {
        expandTrigger: 'hover',
        label: 'cat_name',
        children: 'children',
        value: 'cat_id'
      },
      // 被激活的页签名称
      activeName: 'many',
      // 控制标签页按钮的禁用
      isDisabled: false,
      // 商品分类id
      id: 0,
      manyData: [],
      onlyData: []
    }
  },
  created: function () {
    this.getCateList()
  },
  methods: {
    // 获取所有的商品分类列表
    getCateList: async function () {
      const res = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.warning('商品分类列表获取失败')
      }
      this.catelist = res.data
    },
    // 监听级联选择器的改变
    cascaderChange: function () {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        return ''
      }
      this.getTableData()
    },
    // 发送获取参数列表请求
    getTableData: async function () {
      this.id = this.selectedKeys[2]
      const res = await this.$http.get(`categories/${this.id}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) {
        return this.$message.warning('获取参数列表失败')
      }
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框显示与隐藏
        item.inputVisible = false
        // 文本框中输入的值
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
    },
    // 监听标签页的改变
    handleTabClick: function () {
      if (this.watchBtn) {
        this.manyData = []
        this.onlyData = []
        return this.$message.warning('请选择要查看的商品')
      }
      this.getTableData()
    },
    // 点击添加参数按钮，弹出对话框
    addParams: function () {
      this.$refs.addParams.dialogVisible = true
    },
    // 点击添加属性按钮，弹出对话框
    addAttibute: function () {
      this.$refs.addAttribute.dialogVisible = true
    },
    // 点击按钮，删除静态属性
    deleteAttribute: async function (row) {
      const confirmResult = await this.$confirm('确认删除', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message('已取消删除')
      }
      const res = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.warning('删除静态属性失败')
      }
      this.$message.success('删除静态属性成功')
      this.getTableData()
    },
    // 点击按钮，删除动态参数
    deleteParams: async function (row) {
      const confirmResult = await this.$confirm('确认删除', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message('已取消删除')
      }
      const res = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
      if (res.meta.status !== 200) {
        return this.$message.warning('删除静态属性失败')
      }
      this.$message.success('删除静态属性成功')
      this.getTableData()
    },
    // 点击编辑，弹出参数修改对话框
    editParams: function (row) {
      this.$refs.editParams.row = row
      this.$refs.editParams.dialogVisible = true
    },
    // 点击编辑，弹出属性修改对话框
    editAttribute: function (row) {
      this.$refs.editAttribute.row = row
      this.$refs.editAttribute.dialogVisible = true
    },
    // 文本框失去焦点或摁下 Enter 触发
    handleInputConfirm: async function (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
      }
      // 否则，输入内容需要后续处理
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      const res = await this.$http.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      }).catch(err => err)
      if (res.meta.status !== 200) {
        return this.message.warning('添加标签失败')
      }
      return this.$message.success('添加标签成功')
    },
    // 点击按钮，展示文本输入框
    showInput: function (row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick作用： 就是当页面上的元素呗重新渲染之后，才会指定回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    }
  },
  computed: {
    // 用以监听标签页按钮的禁用
    watchBtn: function () {
      if (this.selectedKeys.length === 3) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-row {
  margin-top: 20px;
  color: #51b6d4;
  .el-cascader {
    margin: 0 10px;
    width: 256px;
  }
}
.btn {
  margin-bottom: 20px;
}
.el-tag {
  margin: 10px;
}
.inputSize {
  width: 120px;
}
</style>
